package org.biubiu0002.baiblog.im.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.biubiu0002.baiblog.im.concurrent.CallbackTask;
import org.biubiu0002.baiblog.im.concurrent.CallbackTaskScheduler;
import org.biubiu0002.baiblog.im.processor.AuthRequestProcessor;
import org.biubiu0002.baiblog.im.session.ServerSession;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 网页成功连接HTTP响应处理
 * @Author: biubiu0002
 * @Date: 2022/9/2 0:24
 **/
@Component
@Slf4j
@ChannelHandler.Sharable
public class HttpAuthRequestHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private AuthRequestProcessor authRequestProcessor;

    /**
     * 成功建立连接后的响应
     * @param ctx channel上下文
     * @param msg Http完整请求报文
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(!(msg instanceof FullHttpRequest)){
            super.channelRead(ctx,msg);
            return;
        }
        FullHttpRequest fullHttpRequest = (FullHttpRequest)msg;
        ServerSession session = new ServerSession(ctx.channel());
        //发起认证请求
        CallbackTaskScheduler.add(new CallbackTask<Boolean>() {
            @Override
            public Boolean execute() throws Exception {
                return authRequestProcessor.action(session,fullHttpRequest);
            }

            @Override
            public void onBack(Boolean b) {
                if(b){
                    try {
                        //登录成功的后续处理 交给WebsocketProtocolHandler 升级协议
                        log.info("登录成功:{}",session.getUser());

                        HttpAuthRequestHandler.super.channelRead(ctx,msg);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                }else{
                    log.info("登录失败:{}",session.getUser());
                }
            }

            @Override
            public void onException(Throwable t) {
                log.error("处理认证出现异常",t);
            }
        });
    }


}
